package com.xgzit.xgzmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xgzit.common.utils.R;
import com.xgzit.xgzmall.cart.feign.ProductFeignService;
import com.xgzit.xgzmall.cart.interceptor.CartInterceptor;
import com.xgzit.xgzmall.cart.service.CartService;
import com.xgzit.xgzmall.cart.vo.Cart;
import com.xgzit.xgzmall.cart.vo.CartItem;
import com.xgzit.xgzmall.cart.vo.SkuInfoVo;
import com.xgzit.xgzmall.cart.vo.UserInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author xgz
 * @Date 2021-06-14 20:34
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "xgzmall:cart:";
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        // 先看一下是否已经添加过这个商品，如果有，修改数量就好了
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            // 购物车没有这个商品
            // 使用多线程 不能直接就干一个线程池，而是配置全局一个，方便管理资源。
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 远程查询要添加的商品信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                // 把商品添加到购物车
                cartItem.setCheck(true);
                cartItem.setCount(1);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            }, executor);

            // 远程查询销售组合信息
            CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValuesTask).get();
            // 转成json再放入redis 方便查看
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);
            return cartItem;
        }else{
            CartItem cartItem = new CartItem();
            // 购物车有这个商品，修改数量
            cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        // 区分是否登录
        UserInfoDto userInfoDto = CartInterceptor.threadLocal.get();
        if (Objects.nonNull(userInfoDto.getUserId())){
            // 登录状态
            String cartKey = CART_PREFIX + userInfoDto.getUserId();
            List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfoDto.getUserKey());
            // 如果临时购物车的数据还没有合并
            if (Objects.nonNull(tempCartItems) && !CollectionUtils.isEmpty(tempCartItems)){
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                // 合并之后清空临时购物车
                clearCart(CART_PREFIX + userInfoDto.getUserKey());
            }
            // 获取登录后的购物车 [包含 合并了的临时购物车数据]
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }else {
            // 没登录
            String cartKey = CART_PREFIX + userInfoDto.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        }
        return cart;
    }


    /**
    * 获取要操作的购物车
    * @return org.springframework.data.redis.core.BoundHashOperations<java.lang.String,java.lang.Object,java.lang.Object>
    */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 1、获取用户信息,根据是否登录 选择离线购物车还是登录的购物车
        String cartKey = "";
        UserInfoDto userInfoDto = CartInterceptor.threadLocal.get();
        if (Objects.nonNull(userInfoDto.getUserId())){
            cartKey = CART_PREFIX + userInfoDto.getUserId();
        }else {
            cartKey = CART_PREFIX + userInfoDto.getUserKey();
        }
        // 绑定一个key方便操作
        return redisTemplate.boundHashOps(cartKey);
    }

    /** 获取购物车 **/
    private List<CartItem> getCartItems(String cartKey){
// 绑定hashkey
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        // values 获取所有的值
        List<Object> values = hashOps.values();
        if (Objects.nonNull(values) && !CollectionUtils.isEmpty(values)){
            return values.stream().map(item -> {
                String str = (String) item;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        // 操作哪一个购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        // 使用json序列化，重新保存
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        // 拿到原来的购物项信息
        CartItem cartItem = getCartItem(skuId);
        // 修改数量、重新保存
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoDto userInfoDto = CartInterceptor.threadLocal.get();
        if (Objects.isNull(userInfoDto)){
            return null;
        }
        String cartKey = CART_PREFIX + userInfoDto.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);
        if(Objects.isNull(cartItems) || CollectionUtils.isEmpty(cartItems)){
            return null;
        }
        // 注意购物车里面的价格 需要查询更新
        // 返回选中的购物项
        return cartItems.stream().filter(CartItem::getCheck).map(item->{
            // 更新价格
            BigDecimal price = productFeignService.getPrice(item.getSkuId());
            item.setPrice(price);
            return item;
        }).collect(Collectors.toList());
    }
}
